package com.fxsen.platform.web.controllers;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fxsen.commons.core.annotation.RecordLog;
import com.fxsen.commons.core.annotation.RequiredPermission;
import com.fxsen.commons.core.base.result.ResponseResult;
import com.fxsen.commons.core.base.result.ResultJson;
import com.fxsen.commons.core.constant.Constants;
import com.fxsen.commons.sysmanager.core.entity.MenuRole;
import com.fxsen.commons.sysmanager.core.entity.Role;
import com.fxsen.commons.sysmanager.core.entity.RolePermission;
import com.fxsen.commons.sysmanager.core.entity.dto.MenuRoleDto;
import com.fxsen.commons.sysmanager.core.entity.dto.RolePermissionDto;
import com.fxsen.commons.sysmanager.core.entity.query.RoleQuery;
import com.fxsen.commons.sysmanager.core.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统角色表(sys_role)表控制层
 *
 * @author <a href="mailto:fuqiang@wisesoft.net.cn">付强</a>
 * @since 2022-01-20 12:52:01
 */
@RestController
@RequestMapping("role")
@RequiredPermission("role")
@Api(tags = "系统：角色接口")
public class RoleController  {
    /**
     * 服务对象
     */
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IMenuRoleService menuRoleService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IRolePermissionService rolePermissionService;
    @Autowired
    private IPermissionService permissionService;
    /**
    * 分页查询所有数据
    * @param page 分页对象
    * @return {@link ResultJson}
    * @date 2022/1/20 14:20
    * @author fxsen
    **/
    @ApiOperation(value = "列表")
    @GetMapping("list")
    @RequiredPermission("role:list")
    public ResponseResult list(@RequestParam(value = "page",required = false,defaultValue = "1") int page,
                               @RequestParam(value = "limit",required = false,defaultValue = "10") int limit, RoleQuery query){
        try {
            LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
            Integer status = query.getStatus();
            String name = query.getName();
            queryWrapper.eq(null != status,Role :: getStatus,status);
            queryWrapper.like(StringUtils.isNotBlank(name),Role :: getName,name);
            queryWrapper.orderByAsc(Role :: getOrderIndex);
            Page<Role> rolePage = this.roleService.page(new Page<Role>(page, limit), queryWrapper);
            List<Role> records = rolePage.getRecords();
            return ResponseResult.success(rolePage);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "保存")
    @PostMapping("save")
    @RecordLog("新增角色")
    @RequiredPermission("role:save")
    public ResponseResult save(@RequestBody Role role, HttpServletRequest request, HttpServletResponse response){
        try {
            if (null == role){
                return ResponseResult.failed("未传请求参数！");
            }
            return roleService.save(role) ? ResponseResult.success() : ResponseResult.saveFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "更新")
    @PostMapping("update")
    @RecordLog("更新角色")
    @RequiredPermission("role:update")
    public ResponseResult update(@RequestBody Role role, HttpServletRequest request, HttpServletResponse response){
        try {
            if (null == role){
                return ResponseResult.failed("未传请求参数！");
            }
            return roleService.updateById(role) ? ResponseResult.success() : ResponseResult.updateFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "删除")
    @GetMapping("delete")
    @RecordLog("删除角色")
    @RequiredPermission("role:delete")
    public ResponseResult delete(@RequestParam("id") String id, HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtils.isBlank(id)){
                return ResponseResult.failed("未传请求参数！");
            }
            Role role = roleService.getById(id);
            if (role.getId().equals("1")){
                return ResponseResult.failed("该角色禁止操作~");
            }
            return roleService.removeById(id) ? ResponseResult.success() : ResponseResult.deleteFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "状态开关")
    @GetMapping("statuSwitch")
    @RecordLog("修改角色状态")
    @RequiredPermission("role:statuSwitch")
    public ResponseResult statuSwitch(@RequestParam("id") String id){
        try {
            Role role = roleService.getById(id);
            if (role.getId().equals("1")){
                return ResponseResult.failed("该角色禁止操作~");
            }
            role.setStatus(role.getStatus().equals(Constants.STATUS_NO) ? Constants.STATUS_YES : Constants.STATUS_NO);
            return roleService.updateById(role) ? ResponseResult.success() : ResponseResult.updateFailed();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "分配菜单")
    @PostMapping("assignMenu")
    @RecordLog("分配菜单")
    @RequiredPermission("role:assignMenu")
    public ResponseResult assignMenu(@RequestBody MenuRoleDto dto){
        try {
            if (null == dto){
                return ResponseResult.success();
            }
            String roleId = dto.getRoleId();
            List<String> menuIds = dto.getMenuIds();
            if (StringUtils.isNotBlank(roleId) && CollectionUtils.isNotEmpty(menuIds)){
                List<MenuRole> menuRoleList = menuRoleService.findByRoleId(roleId);
                if (CollectionUtils.isNotEmpty(menuRoleList)){
                    menuRoleList.forEach(menuRole -> {
                        menuRoleService.removeById(menuRole.getId());
                    });
                }
                List<MenuRole> list = new ArrayList<>();
                for (String menuId : menuIds) {
                    MenuRole menuRole = new MenuRole();
                    menuRole.setRoleId(roleId);
                    menuRole.setMenuId(menuId);
                    list.add(menuRole);
                }
                menuRoleService.saveBatch(list);
            }
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
    @ApiOperation(value = "分配权限")
    @PostMapping("assignPermission")
    @RecordLog("分配权限")
    @RequiredPermission("role:assignPermission")
    public ResponseResult assignPermission(@RequestBody RolePermissionDto dto, HttpServletRequest request){
        try {
            if (null == dto){
                return ResponseResult.success();
            }
            String roleId = dto.getRoleId();
            List<String> permissionIds = dto.getPermissionIds();
            if (CollectionUtils.isNotEmpty(permissionIds) && StringUtils.isNotBlank(roleId)){
                List<RolePermission> rolePermissions = rolePermissionService.findByRoleId(roleId);
                if (CollectionUtils.isNotEmpty(rolePermissions)){
                    rolePermissions.forEach(rolePermission -> {
                        rolePermissionService.removeById(rolePermission);
                    });
                }
                List<RolePermission> list = new ArrayList<>();
                for (String permissionId : permissionIds) {
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(permissionId);
                    list.add(rolePermission);
                }
                rolePermissionService.saveBatch(list);
            }
            return ResponseResult.success();
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.failed();
        }
    }
}
